class Profile < ActiveRecord::Base
  has_one :user
  belongs_to :group
  has_one :faculty, :through => :group
  after_initialize :generate_uid
  
  validates_presence_of :name, :surname, :phone, :uid, :group_id
  validates :phone, :phone => true
  
  def generate_uid
    return unless new_record?
    begin
      uid = RandSmartPass(7) 
    end while Profile.count(:conditions =>  [ "uid = ?", uid ]) != 0
    self[:uid] = uid
  end
  
  def RandSmartPass(size = 6)
    c = %w(b c d f g h j k l m n p qu r s t v w x z ch cr fr nd ng nk nt ph pr rd sh sl sp st th tr lt)
    v = %w(a e i o u y)
    f, r = true, ''

    size.times do
      r << (f ? c[rand * c.size] : v[rand * v.size])
      f = !f
    end
    
    r    
  end
  
  def assign_attributes(new_attributes, options = {})
    if !new_attributes[:group].nil?
      new_attributes[:group] = Group.find(new_attributes[:group])
    end
    if !new_attributes[:faculty].nil?
      new_attributes[:faculty] = nil
    end
    super(new_attributes, options = {})
  end
end
